package com.mvc.web;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.mvc.model.User;

/**
 * 页面对象传递，单个对象及集合
 * @author Sunlight
 *
 */
@Controller
@RequestMapping(value="user")
public class UserController {
	private List<User> users=new ArrayList<User>();
	/**
	 * 初始化数据
	 */
	public UserController() {
		users.add(new User(1,"User1",18,"用户1","abcd@123.com"));
		users.add(new User(2,"User2",28,"用户2","abcd@123.com"));
		users.add(new User(3,"User3",38,"用户3","abcd@123.com"));
		users.add(new User(4,"User4",48,"用户4","abcd@123.com"));
		users.add(new User(5,"User5",58,"用户5","abcd@123.com"));
	}
	/**
	 * 加载数据列表
	 * @param model
	 * @return
	 */
	@RequestMapping(value={"/users","/list","/"})
	public String list(Model model){
		System.out.println("Load a User!");
		model.addAttribute("users", users);
		return "user";
	}
	
	/**
	 * 加载单个对象
	 * @param model
	 * @return
	 */
	@RequestMapping(value={"/user","/model"})
	public String load(Model model){
		System.out.println("Load a User!");
		User user=new User();
		user.setId(222);
		user.setUsername("my is a user ");
		user.setAge(22);
		user.setNickname("我是一个用户");
		user.setEmail("xxxx@xxx.com");
		model.addAttribute("user", user);
		return "user";
	}
	/**
	 * 打开添加对象页面 get
	 * @param model初始化User 对象方法1
	 * @return
	 */
	@RequestMapping(value={"/add","/add.get"},method=RequestMethod.GET)
	public String add(Model model){
		System.out.println("User is Page!");
		model.addAttribute(new User());
		return "add_user";
	}
	/**
	 * 打开添加对象页面 get
	 * @param user 初始化User 对象方法2
	 * @return
	 */
	@RequestMapping(value={"/save","/save.get"},method=RequestMethod.GET)
	public String add_other(@ModelAttribute("user")User user){
		System.out.println("User is Page to @ModelAttribute!");
		return "add_user";
	}
	
	/**
	 * 添加表单提交页面
	 * @param user
	 * @return
	 */
	@RequestMapping(value={"/save","/add"},method=RequestMethod.POST)
	public String add(User user){
		System.out.println("User is Save!");
		users.add(user);
		System.out.println(user);
		return "user";
	}
	/**
	 * 删除对象处理方法
	 * @param id 参数为必须输入的
	 * @return
	 */
	@RequestMapping(value={"/delete","/del"})
	public String delete(@RequestParam int index){
		System.out.println("User is Delete!");
		System.out.println("delete id is "+index);
		users.remove(index);
		return "redirect:/user/list";
	}
	
	
	
}
